/*
 * Copyright (c) 2017 Qunar.com. All Rights Reserved.
 */
package com.guoyu.project.common.freemarker;

import java.io.IOException;
import java.util.Map;

import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

/**
 * @author: libo Date: 17-3-1 Time: 上午11:12
 * @version: \$Id$
 */
public class OverrideDirective implements TemplateDirectiveModel {

    public final static String DIRECTIVE_NAME = "override";

    public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body)
            throws TemplateException, IOException {
        String name = FreemarkerSupports.getRequiredArgument(params, "name");
        String overrideVariableName = FreemarkerSupports.getOverrideVariableName(name);

        OverrideBodyWrapper override = FreemarkerSupports.getOverrideBody(env, name);
        OverrideBodyWrapper current = new OverrideBodyWrapper(body, env);
        if (override == null) {
            env.setVariable(overrideVariableName, current);
        } else {
            FreemarkerSupports.setParentForTop(current, override);
        }
    }
}
